package com.xps.charmingshop.view.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.jude.utils.JUtils;
import com.xps.charmingshop.R;
import com.xps.charmingshop.bean.UpdateMenuBean;
import com.xps.charmingshop.bean.UpdateMenuInformationBean;
import com.xps.charmingshop.date.net.UserNetWorks;
import com.xps.charmingshop.servicer.UserService;
import com.xps.charmingshop.servicer.UserServiceImpl;
import com.xps.charmingshop.utils.DensityUtil;
import com.xps.charmingshop.utils.SharedPreferencesUtils;
import com.xps.charmingshop.view.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * Created by MI on 2018/1/25.
 */

public class UpdateMenuActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.actionbar_tv_title)
    TextView actionbarTvTitle;
    String dish_id = null;
    @BindView(R.id.Text_ProductName)
    TextView TextProductName;
    @BindView(R.id.Text_ClassificationOne)
    TextView TextClassificationOne;
    @BindView(R.id.Text_OriginalPrice)
    TextView TextOriginalPrice;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.Text_Discount)
    TextView TextDiscount;
    @BindView(R.id.Text_ConcessionalRate)
    TextView TextConcessionalRate;
    @BindView(R.id.Text_Picture)
    LinearLayout TextPicture;
    @BindView(R.id.Text_Introduce)
    TextView TextIntroduce;
    @BindView(R.id.Text_Mandatory)
    LinearLayout TextMandatory;
    @BindView(R.id.Text_Optional)
    LinearLayout TextOptional;
    AlertDialog dialog;
    LayoutInflater layoutInflater;
    LinearLayout Layout_Classification;
    View longinDialogView;

    String[] Optional = {};
    List<String> OptionalArray;

    String[] str = {};
    List<String> strArray;

    String[] Imagestr = {};
    List<String> ImageArray;


    View MustView;
    Dialog MustDialog;
    EditText Must_Name;
    EditText Must_Price;
    ViewGroup.MarginLayoutParams params;
    TextView Button_OK;

    View OptionalView;
    Dialog OptionalDialog;
    EditText Optional_Name;
    EditText Optional_Price;
    ViewGroup.MarginLayoutParams Optionalparams;
    TextView Button_Optional;

    String dish_sort_id;
    Dialog bottomDialog;
    TextView XiCe_pickPhoto;
    TextView XiJi_takePhoto;
    TextView cancel_TextView;
    @BindView(R.id.iv_dishName_change)
    ImageView ivDishNameChange;
    @BindView(R.id.iv_main_chenge)
    ImageView ivMainChenge;
    @BindView(R.id.iv_youhui_change)
    ImageView ivYouhuiChange;
    @BindView(R.id.iv_youhuijia_change)
    ImageView ivYouhuijiaChange;
    @BindView(R.id.iv_include_change)
    ImageView ivIncludeChange;
    @BindView(R.id.Text_Name_detials)
    TextView TextNameDetials;
    @BindView(R.id.Text_ClassificationTwo)
    TextView TextClassificationTwo;
    @BindView(R.id.iv_Original_change)
    ImageView ivOriginalChange;
    @BindView(R.id.Must_Add)
    TextView MustAdd;
    @BindView(R.id.Optional_Add)
    TextView OptionalAdd;
    @BindView(R.id.Button_UpdateMenu)
    TextView ButtonUpdateMenu;
    @BindView(R.id.Button_Finsh)
    TextView ButtonFinsh;
    private ImageView textView;
    private Uri imageUri;  //图片保存路径
    private TakePhoto takePhoto;
    private CropOptions cropOptions;  //裁剪参数
    private CompressConfig compressConfig;  //压缩参数
    private InvokeParam invokeParam;
    private UserService userService = new UserServiceImpl();
    private String ImageStr;
    private String dish_name;


    @Override
    protected int getLayout() {
        return R.layout.activity_updatemenu;
    }

    @Override
    protected void setData() {
        actionbarTvTitle.setText("修改菜品信息");
        actionbarTvTitle.setTextColor(getResources().getColor(R.color.white));
    }

    @Override
    protected void init(Bundle inBundle) {
        ButterKnife.bind(this);
        getTakePhoto().onCreate(inBundle);
        Intent intent = getIntent();
        dish_id = intent.getStringExtra("dish_id");
        dish_name = intent.getStringExtra("shop_name");
        TextNameDetials.setText(dish_name);
        Log.e("fff", dish_name);
        getUpdateMenu();
        layoutInflater = LayoutInflater.from(UpdateMenuActivity.this);
        AlertDialog.Builder builder = new AlertDialog.Builder(UpdateMenuActivity.this);
        dialog = builder.create();
        longinDialogView = layoutInflater.inflate(R.layout.dialog_classification, null);
        dialog.setView(longinDialogView);
        Layout_Classification = longinDialogView.findViewById(R.id.Layout_Classification);

        strArray = new ArrayList<String>();
        strArray.addAll(Arrays.asList(str));

        OptionalArray = new ArrayList<String>();
        OptionalArray.addAll(Arrays.asList(Optional));

        ImageArray = new ArrayList<String>();
        ImageArray.addAll(Arrays.asList(Imagestr));

        MustDialog = new Dialog(this, R.style.BottomDialog);
        MustView = LayoutInflater.from(this).inflate(R.layout.dialog_must, null);
        MustDialog.setContentView(MustView);
        params = (ViewGroup.MarginLayoutParams) MustView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        params.bottomMargin = DensityUtil.dp2px(this, 8f);
        MustView.setLayoutParams(params);
        MustDialog.setCanceledOnTouchOutside(true);
        MustDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        Must_Name = MustView.findViewById(R.id.Must_Name);
        Must_Price = MustView.findViewById(R.id.Must_Price);
        Button_OK = MustView.findViewById(R.id.Button_OK);
        Button_OK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((Must_Name.getText().toString().equals("") || Must_Name.getText().toString() == null) && (Must_Price.getText().toString().equals("") || Must_Price.getText().toString() == null)) {
                    JUtils.Toast("添加失败");
                } else {
                    showMustDialog();
                }
                MustDialog.dismiss();
            }
        });


        OptionalDialog = new Dialog(this, R.style.BottomDialog);
        OptionalView = LayoutInflater.from(this).inflate(R.layout.dialog_optional, null);
        OptionalDialog.setContentView(OptionalView);
        Optionalparams = (ViewGroup.MarginLayoutParams) MustView.getLayoutParams();
        Optionalparams.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        Optionalparams.bottomMargin = DensityUtil.dp2px(this, 8f);
        OptionalView.setLayoutParams(Optionalparams);
        OptionalDialog.setCanceledOnTouchOutside(true);
        OptionalDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        Optional_Name = OptionalView.findViewById(R.id.Optional_Name);
        Optional_Price = OptionalView.findViewById(R.id.Optional_Price);
        Button_Optional = OptionalView.findViewById(R.id.Button_Optional);
        Button_Optional.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((Optional_Name.getText().toString().equals("") || Optional_Name.getText().toString() == null) && (Optional_Price.getText().toString().equals("") || Optional_Price.getText().toString() == null)) {
                    JUtils.Toast("添加失败");
                } else {
                    showOptionalDialog();
                }
                OptionalDialog.dismiss();
            }
        });


        bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        params.bottomMargin = DensityUtil.dp2px(this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setText("相册");
        XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setText("相机");
        cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        layoutInflater = LayoutInflater.from(UpdateMenuActivity.this);

        initData();
    }

    public void getUpdateMenu() {
        String user_token = SharedPreferencesUtils.getString("user_token", "String", null);
        UserNetWorks.getUpdateMenu(user_token, dish_id, new Subscriber<UpdateMenuBean>() {


            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(UpdateMenuBean updateMenuBean) {
                if (updateMenuBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast("获取成功");
                    TextProductName.setText(updateMenuBean.getReturn_body().getDish_name());
                    TextIntroduce.setText(updateMenuBean.getReturn_body().getDish_description());
                    TextDiscount.setText(updateMenuBean.getReturn_body().getDish_discount_price());
                    TextOriginalPrice.setText(updateMenuBean.getReturn_body().getDish_price());
                    TextConcessionalRate.setText(Float.parseFloat(updateMenuBean.getReturn_body().getDish_price()) - Float.parseFloat(updateMenuBean.getReturn_body().getDish_discount_price()) + "");
                    TextClassificationOne.setText(updateMenuBean.getReturn_body().getSort_name());
                    dish_sort_id = updateMenuBean.getReturn_body().getDish_sort_id();
                    List<UpdateMenuBean.ReturnBodyBean.DishSortBean> list = updateMenuBean.getReturn_body().getDish_sort();
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            addOrderItem(list.get(i), Layout_Classification);
                            addDividerLine(Layout_Classification);
                        }
                    }
                    List<UpdateMenuBean.ReturnBodyBean.DishMustBean> dishMustBeen = updateMenuBean.getReturn_body().getDish_must();
                    if (dishMustBeen != null && dishMustBeen.size() > 0) {
                        for (int i = 0; i < dishMustBeen.size(); i++) {
                            addDishMustBeenItem(dishMustBeen.get(i), TextMandatory);
                            addDividerLine(TextMandatory);
                            strArray.add("{\"must_name\":\"" + dishMustBeen.get(i).getMust_name() + "\",\"must_price\":\"" + dishMustBeen.get(i).getMust_price() + "\"}");
                        }

                    }
                    List<UpdateMenuBean.ReturnBodyBean.DishOptionalBean> dishOptionalBeen = updateMenuBean.getReturn_body().getDish_optional();
                    if (dishOptionalBeen != null && dishOptionalBeen.size() > 0) {
                        for (int i = 0; i < dishOptionalBeen.size(); i++) {
                            addDishOptionalBeenItem(dishOptionalBeen.get(i), TextOptional);
                            addDividerLine(TextOptional);
                            OptionalArray.add("{\"optional_name\":\"" + dishOptionalBeen.get(i).getOptional_name() + "\",\"optional_price\":\"" + dishOptionalBeen.get(i).getOptional_price() + "\"}");
                        }
                    }
                    List<UpdateMenuBean.ReturnBodyBean.DishPicSrcBean> dishPicSrcBeen = updateMenuBean.getReturn_body().getDish_pic_src();
                    if (dishPicSrcBeen != null && dishPicSrcBeen.size() > 0) {
                        for (int i = 0; i < dishPicSrcBeen.size(); i++) {
                            addImageItem(dishPicSrcBeen.get(i), TextPicture);
                            ImageArray.add("{\"pic_src\":\"" + dishPicSrcBeen.get(i).getPic_src() + "\"}");
                            System.out.println(ImageArray);
                        }

                    }
                }
            }
        });
    }


    @OnClick({R.id.actionbar_iv_back, R.id.Button_Finsh, R.id.iv_dishName_change, R.id.Button_UpdateMenu,
            R.id.Optional_Add, R.id.Must_Add, R.id.iv_main_chenge, R.id.iv_Original_change, R.id.iv_youhui_change, R.id.iv_youhuijia_change, R.id.iv_include_change})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.iv_dishName_change:
                showInputDialog(TextProductName, "3");
                break;
            case R.id.iv_main_chenge:
                dialog.show();
                break;
            case R.id.iv_Original_change:
                showInputDialog(TextOriginalPrice, "1");
                break;
            case R.id.iv_youhui_change:
                showInputDialog(TextDiscount, "2");
                break;
            case R.id.iv_youhuijia_change:
                //  showInputDialog(TextConcessionalRate);
                break;
            case R.id.iv_include_change:
                showInputDialog(TextIntroduce, "3");
                break;
            case R.id.Must_Add:
                MustDialog.show();
                break;
            case R.id.Optional_Add:
                OptionalDialog.show();
                break;
            case R.id.Button_UpdateMenu:
                showDialog();
                getUpdateMenuInformation();
                break;
            case R.id.Button_Finsh:
                finish();
                break;
        }
    }

    /**
     * 添加分割线
     */
    public void addDividerLine(LinearLayout ll_lv) {
        View v = new View(UpdateMenuActivity.this);
        v.setAlpha(0.5f);
        v.setBackgroundColor(UpdateMenuActivity.this.getResources().getColor(R.color.dialogplus_card_shadow));
        v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
        ll_lv.addView(v);
    }

    /**
     * 分类
     * addOrderItem(DingDanBean.ReturnBodyBean dataBean)
     */
    public void addOrderItem(final UpdateMenuBean.ReturnBodyBean.DishSortBean dataBean, LinearLayout ll_lv) {
        View view = LayoutInflater.from(UpdateMenuActivity.this).inflate(R.layout.classification_item_fan, null);
        TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        Text_Classification.setText(dataBean.getSort_name());
        Text_Classification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextClassificationOne.setText(dataBean.getSort_name());
                dish_sort_id = dataBean.getSort_id();
                dialog.dismiss();
            }
        });
        ll_lv.addView(view);
    }

    /**
     * 可选项
     * addOrderItem(DingDanBean.ReturnBodyBean dataBean)
     */
    public void addDishMustBeenItem(final UpdateMenuBean.ReturnBodyBean.DishMustBean dataBean, LinearLayout ll_lv) {
        final View view = LayoutInflater.from(UpdateMenuActivity.this).inflate(R.layout.classification_item, null);
        final TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        final TextView Text_Qian = view.findViewById(R.id.Text_Qian);
        final TextView tvDelete = (TextView) view.findViewById(R.id.tv_delete);
        final TextView tvChange = (TextView) view.findViewById(R.id.tv_xiugai);
        Text_Classification.setText(dataBean.getMust_name());
        Text_Qian.setText(dataBean.getMust_price());
        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < strArray.size(); i++) {
                    if (strArray.get(i).equals("{\"must_name\":\"" + dataBean.getMust_name() + "\",\"must_price\":\"" + dataBean.getMust_price() + "\"}"))
                        strArray.remove(i);
                }
                view.setVisibility(View.GONE);
                System.out.println(strArray);
            }
        });
        tvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                strDialog(dataBean.getMust_name(), dataBean.getMust_price(), Text_Classification);
            }
        });
        ll_lv.addView(view);
    }

    /**
     * 可选项
     * addOrderItem(DingDanBean.ReturnBodyBean dataBean)
     */
    public void addDishOptionalBeenItem(final UpdateMenuBean.ReturnBodyBean.DishOptionalBean dataBean, LinearLayout ll_lv) {
        final View view = LayoutInflater.from(UpdateMenuActivity.this).inflate(R.layout.classification_item, null);
        final TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        final TextView Text_Qian = view.findViewById(R.id.Text_Qian);
        final TextView Text_JiaGe = view.findViewById(R.id.Text_JiaGe);
        Text_Classification.setText(dataBean.getOptional_name());
        Text_Qian.setText(dataBean.getOptional_price());
        final TextView tvDelete = (TextView) view.findViewById(R.id.tv_delete);
        final TextView tvChange = (TextView) view.findViewById(R.id.tv_xiugai);
        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < OptionalArray.size(); i++) {
                    if (OptionalArray.get(i).equals("{\"optional_name\":\"" + dataBean.getOptional_name() + "\",\"optional_price\":\"" + dataBean.getOptional_price() + "\"}"))
                        OptionalArray.remove(i);
                }
                view.setVisibility(View.GONE);
            }
        });
        tvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OptionalDialog(dataBean.getOptional_name(), dataBean.getOptional_price(), view);
            }
        });
        ll_lv.addView(view);
    }

    public void strDialog(final String name, final String price, final View Text_Classification) {
        final Dialog OptionalDialog = new Dialog(this, R.style.BottomDialog);
        View OptionalView = LayoutInflater.from(this).inflate(R.layout.dialog_optional, null);
        OptionalDialog.setContentView(OptionalView);
        ViewGroup.MarginLayoutParams Optionalparams = (ViewGroup.MarginLayoutParams) MustView.getLayoutParams();
        Optionalparams.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        Optionalparams.bottomMargin = DensityUtil.dp2px(this, 8f);
        OptionalView.setLayoutParams(Optionalparams);
        OptionalDialog.setCanceledOnTouchOutside(true);
        OptionalDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        final EditText Optional_Name = OptionalView.findViewById(R.id.Optional_Name);
        final EditText Optional_Price = OptionalView.findViewById(R.id.Optional_Price);
        Optional_Name.setText(name);
        Optional_Price.setText(price);
        TextView Button_Optional = OptionalView.findViewById(R.id.Button_Optional);
        Button_Optional.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < strArray.size(); i++) {
                    if (strArray.get(i).equals("{\"must_name\":\"" + name + "\",\"must_price\":\"" + price + "\"}"))
                        strArray.remove(i);
                }
                strArray.add("{\"must_name\":\"" + Optional_Name.getText().toString() + "\",\"must_price\":\"" + Optional_Price.getText().toString() + "\"}");
                addMustItem(Optional_Name.getText().toString(), Optional_Price.getText().toString(), "{\"must_name\":\"" + Optional_Name.getText().toString() + "\",\"must_price\":\"" + Optional_Price.getText().toString() + "\"}", TextMandatory);
                addDividerLine(TextMandatory);
                Text_Classification.setVisibility(View.GONE);
                OptionalDialog.dismiss();
            }
        });
        OptionalDialog.show();
    }

    public void OptionalDialog(final String name, final String price, final View Text_Classification) {
        final Dialog OptionalDialog = new Dialog(this, R.style.BottomDialog);
        View OptionalView = LayoutInflater.from(this).inflate(R.layout.dialog_optional, null);
        OptionalDialog.setContentView(OptionalView);
        ViewGroup.MarginLayoutParams Optionalparams = (ViewGroup.MarginLayoutParams) MustView.getLayoutParams();
        Optionalparams.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        Optionalparams.bottomMargin = DensityUtil.dp2px(this, 8f);
        OptionalView.setLayoutParams(Optionalparams);
        OptionalDialog.setCanceledOnTouchOutside(true);
        OptionalDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        final EditText Optional_Name = OptionalView.findViewById(R.id.Optional_Name);
        final EditText Optional_Price = OptionalView.findViewById(R.id.Optional_Price);
        Optional_Name.setText(name);
        Optional_Price.setText(price);
        TextView Button_Optional = OptionalView.findViewById(R.id.Button_Optional);
        Button_Optional.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < OptionalArray.size(); i++) {
                    if (OptionalArray.get(i).equals("{\"optional_name\":\"" + name + "\",\"optional_price\":\"" + price + "\"}"))
                        OptionalArray.remove(i);
                }
                OptionalArray.add("{\"optional_name\":\"" + Optional_Name.getText().toString() + "\",\"optional_price\":\"" + Optional_Price.getText().toString() + "\"}");
                addOptionalItem(Optional_Name.getText().toString(), Optional_Price.getText().toString(), Optional_Price.getText().toString(), TextOptional);
                addDividerLine(TextOptional);
                Text_Classification.setVisibility(View.GONE);
                OptionalDialog.dismiss();
            }
        });
        OptionalDialog.show();
    }


    private void showMustDialog() {
        strArray.add("{\"must_name\":\"" + Must_Name.getText().toString() + "\",\"must_price\":\"" + Must_Price.getText().toString() + "\"}");
        addMustItem(Must_Name.getText().toString(), Must_Price.getText().toString(), "{\"must_name\":\"" + Must_Name.getText().toString() + "\",\"must_price\":\"" + Must_Price.getText().toString() + "\"}", TextMandatory);
        System.out.println(strArray);
        addDividerLine(TextMandatory);
    }


    private void showOptionalDialog() {
        OptionalArray.add("{\"optional_name\":\"" + Optional_Name.getText().toString() + "\",\"optional_price\":\"" + Optional_Price.getText().toString() + "\"}");
        addOptionalItem(Optional_Name.getText().toString(), Optional_Price.getText().toString(), Optional_Price.getText().toString(), TextOptional);
        System.out.println(OptionalArray);
        addDividerLine(TextOptional);
    }

    /**
     * 可选项
     * addOrderItem(DingDanBean.ReturnBodyBean dataBean)
     */
    public void addMustItem(final String str, final String qian, final String set, LinearLayout ll_lv) {
        final View view = LayoutInflater.from(UpdateMenuActivity.this).inflate(R.layout.classification_item, null);
        final TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        final TextView Text_Qian = view.findViewById(R.id.Text_Qian);
        Text_Classification.setText(str);
        Text_Qian.setText(qian);
        final TextView tvDelete = (TextView) view.findViewById(R.id.tv_delete);
        final TextView tvChange = (TextView) view.findViewById(R.id.tv_xiugai);
        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < strArray.size(); i++) {
                    if (strArray.get(i).equals(set))
                        strArray.remove(i);
                }
                Text_Classification.setVisibility(View.GONE);
                tvDelete.setVisibility(View.GONE);
                tvChange.setVisibility(View.GONE);
                System.out.println(strArray);
            }
        });
        tvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                strDialog(str, qian, view);
            }
        });
        ll_lv.addView(view);
    }

    /**
     * 可选项
     * addOrderItem(DingDanBean.ReturnBodyBean dataBean)
     */
    public void addOptionalItem(final String str, final String qian, final String set, LinearLayout ll_lv) {
        final View view = LayoutInflater.from(UpdateMenuActivity.this).inflate(R.layout.classification_item, null);
        final TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        final TextView Text_Qian = view.findViewById(R.id.Text_Qian);
        Text_Classification.setText(str);
        Text_Qian.setText(qian);
        final TextView tvDelete = (TextView) view.findViewById(R.id.tv_delete);
        final TextView tvChange = (TextView) view.findViewById(R.id.tv_xiugai);
        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < OptionalArray.size(); i++) {
                    if (OptionalArray.get(i).equals("{\"optional_name\":\"" + str + "\",\"optional_price\":\"" + set + "\"}"))
                        OptionalArray.remove(i);
                }
                Text_Classification.setVisibility(View.GONE);
                tvDelete.setVisibility(View.GONE);
                tvChange.setVisibility(View.GONE);
            }
        });
        tvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OptionalDialog(str, qian, view);
            }
        });
        ll_lv.addView(view);
    }

    public void getUpdateMenuInformation() {
        String user_token = SharedPreferencesUtils.getString("user_token", "String", null);
        UserNetWorks.getUpdateMenuInformation(user_token, dish_id, TextProductName.getText().toString(), dish_sort_id, TextOriginalPrice.getText().toString(), TextDiscount.getText().toString(), ImageArray + "", TextIntroduce.getText().toString(), strArray + "", OptionalArray + "", new Subscriber<UpdateMenuInformationBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onNext(UpdateMenuInformationBean updateMenuInformationBean) {
                dissmisDialog();
                if (updateMenuInformationBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(updateMenuInformationBean.getReturn_msg());
                    finish();
                } else {
                    JUtils.Toast(updateMenuInformationBean.getReturn_msg());
                }
            }
        });
    }

    /**
     * 可选项
     * addOrderItem(DingDanBean.ReturnBodyBean dataBean)
     */
    public void addImageItem(final UpdateMenuBean.ReturnBodyBean.DishPicSrcBean dishPicSrcBean, LinearLayout ll_lv) {
        View view = LayoutInflater.from(UpdateMenuActivity.this).inflate(R.layout.classification_item_image, null);
        final ImageView image_updatemenu = view.findViewById(R.id.image_updatemenu);
        Glide.with(UpdateMenuActivity.this).load("http://" + dishPicSrcBean.getPic_src())
                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                .into(image_updatemenu);
        image_updatemenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView = image_updatemenu;
                ImageStr = dishPicSrcBean.getPic_src();
                OnClick();
            }
        });
        ll_lv.addView(view);
    }

    void OnClick() {
        bottomDialog.show();
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                //从相册中选取图片并裁剪
                takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                bottomDialog.dismiss();
            }
        });
        XiJi_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                //拍照并裁剪
                takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                bottomDialog.dismiss();
            }
        });
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    private void initData() {
        //获取TakePhoto实例
        takePhoto = getTakePhoto();
        //设置裁剪参数
        cropOptions = new CropOptions.Builder().setAspectX((int) 0.5).setAspectY((int) 0.5).setWithOwnCrop(false).create();
        //设置压缩参数
        compressConfig = new CompressConfig.Builder().setMaxSize(1 * 1).setMaxPixel(1).create();
        takePhoto.onEnableCompress(compressConfig, true);  //设置为需要压缩
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void takeSuccess(TResult result) {
        String iconPath = result.getImage().getOriginalPath();
        Glide.with(this).load(iconPath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                .into(textView);
        getUploadImage(iconPath);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Toast.makeText(UpdateMenuActivity.this, "Error:" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeCancel() {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    public void getUploadImage(String imageUri) {
        Uri uri = getImageContentUri(UpdateMenuActivity.this, getFilePath(imageUri));
        if (uri == null) {
            Toast.makeText(this, "你没有选择任何图片", Toast.LENGTH_LONG).show();
        } else {
            String path = null;
            String[] pojo = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(uri, pojo, null, null, null);
            if (cursor != null) {
                int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                cursor.moveToFirst();
                path = cursor.getString(columnIndex);
                cursor.close();
            }
            if (path != null) {
                doUpload(path);
            }
        }
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    File getFilePath(String str) {
        File Gallery = new File(str);
        if (!Gallery.getParentFile().exists()) Gallery.getParentFile().mkdirs();
        return Gallery;
    }

    private void doUpload(final String pathName) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    //文件二进制数据
                    InputStream in = new FileInputStream(new File(pathName));
                    //普通字符串数据
                    Map<String, String> data = new HashMap<String, String>();
                    final String result = userService.userUpload(in, data, pathName);
                    Log.i("asdasd", result);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getString("return_code").equals("SUCCESS")) {
                                    for (int i = 0; i < ImageArray.size(); i++) {
                                        if (ImageArray.get(i).equals("{\"pic_src\":\"" + ImageStr + "\"}"))
                                            ImageArray.remove(i);
                                    }
                                    ImageArray.add("{\"pic_src\":\"" + jsonObject.getString("return_body") + "\"}");
                                    System.out.println(ImageArray);
                                    Toast.makeText(UpdateMenuActivity.this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                                } else if (jsonObject.getString("return_code").equals("FAIL")) {
                                    Toast.makeText(UpdateMenuActivity.this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(UpdateMenuActivity.this, "上传错误", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    private void showInputDialog(final TextView textView, final String str) {
        final EditText editText = new EditText(UpdateMenuActivity.this);
        editText.setBackground(null);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(UpdateMenuActivity.this);
        inputDialog.setTitle("请输入您要修改的信息").setView(editText);
        editText.setText(textView.getText().toString());
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        textView.setText(editText.getText().toString());
                        if (str.equals("1")) {
                            TextConcessionalRate.setText(Float.valueOf(editText.getText().toString()) - Float.valueOf(TextDiscount.getText().toString()) + "");
                        } else if (str.equals("2")) {
                            TextConcessionalRate.setText(Float.valueOf(TextOriginalPrice.getText().toString()) - Float.valueOf(editText.getText().toString()) + "");
                        }
                    }
                }).show();
    }
}
